﻿using NanoMvvm.Collections;

namespace NanoMvvm
{
    public class SelectionDialogViewModel : WorkspaceViewModel
    {
        private string message;

        private string header;

        private int selectionIndex;

        private string selectionText;

        // design-time support
        public SelectionDialogViewModel() : this(new string[] { })
        {
            InitializeDesignTimeData();
        }

        public SelectionDialogViewModel(params string[] list)
        {
            Items = new ObservableList<CommandViewModel<DelegateCommand<string>>>();

            var command = new DelegateCommand<string>(Select);

            foreach (var s in list)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    Items.Add(new CommandViewModel<DelegateCommand<string>>(s, command));
                }
            }

            selectionIndex = -1;

            Selection = null;
        }

        public ObservableList<CommandViewModel<DelegateCommand<string>>> Items { get; private set; }

        public string Message
        {
            get
            {
                return message;
            }
            set
            {
                SetProperty(ref message, value, () => Message);
            }
        }

        public string Header
        {
            get
            {
                return header;
            }
            set
            {
                SetProperty(ref header, value, () => Header);
            }
        }

        public int SelectionIndex
        {
            get { return selectionIndex; }
            private set { SetProperty(ref selectionIndex, value, () => SelectionIndex); }
        }

        public string Selection
        {
            get { return selectionText; }
            private set { SetProperty(ref selectionText, value, () => Selection); }
        }

        protected override void OnDesignTimeInit()
        {
            base.OnDesignTimeInit();

            Header = "Test Header";
            Message = "This is a test message.";

            Items.Add(new CommandViewModel<DelegateCommand<string>>("OK", new DelegateCommand<string>(obj => { })));
            Items.Add(new CommandViewModel<DelegateCommand<string>>("Cancel", new DelegateCommand<string>(obj => { })));
        }

        private void Select(string selectedText)
        {
            for (int i = 0; i < Items.Count; i++)
            {
                var viewModel = Items[i];
                if (viewModel.Header == selectedText)
                {
                    SelectionIndex = i;
                    break;
                }
            }

            if (SelectionIndex >= 0)
            {
                Selection = selectedText;
            }

            Deactivate();
        }
    }
}